package com.hubiwei.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

public class DimUtil {
    public static JSONObject getDimFromPhoenix(Connection phoenixConn,
                                               String table,
                                               Long id) {
        String sql = "select * from " + table + " where id=?";
        Object[] args = {id.toString()};
        
        List<JSONObject> result = JdbcUtil.queryList(phoenixConn, sql, args, JSONObject.class);
        
        return result.size() == 1 ? result.get(0) : null;
    }
    
    public static JSONObject getDim(Connection phoenixConn,
                                    Jedis redisClient,
                                    String table,
                                    Long id) {
        // 1. 先从redis获取
        JSONObject dim = getDimFromRedis(redisClient, table, id);
        // 3. 获取不到从Phoenix获取, 结果返回. 把结果写入到redis
        if (dim == null) {  // 没有获取到
            System.out.println(table + " " + id + " 走的数据库");
            dim = getDimFromPhoenix(phoenixConn, table, id);
            // 把维度数据写入到redis中
            writeToRedis(redisClient, table, id, dim);
            
        }else{
            System.out.println(table + " " + id + " 走的缓存");
        }
        // 2. 获取到了信息, 则直接返回
        return dim;
    }
    
    private static void writeToRedis(Jedis redisClient,
                                     String table,
                                     Long id,
                                     JSONObject dim) {
        String key = table + ":" + id;
        String value = dim.toJSONString();
        
        /*redisClient.set(key, value);
        redisClient.expire(key, 3 * 24 * 60 * 60);  // 给key设置过期时间3天*/
        redisClient.setex(key, 3 * 24 * 60 * 60, value);
        
    }
    
    private static JSONObject getDimFromRedis(Jedis redisClient, String table, Long id) {
        String key = table + ":" + id;
    
        String dim = redisClient.get(key);  // 如果缓存不存在, 就是null
    
        return dim == null ? null : JSON.parseObject(dim);
    }
    
}
